<template>
	<view>
		<cu-custom bgColor="bg-gradual-pink" :isBack="true">
			<block slot="backText">返回</block>
			<block slot="content">新增现场施工</block>
		</cu-custom>
		<form>
			<view class="cu-form-group">
				<view class="title">现场标题</view>
				<input placeholder="请输入标题" name="input" v-model="myFormData.emergencyTitle"></input>
			</view>
			<view class="cu-form-group">
				<view class="title">位置</view>
				<textarea placeholder="请输入位置" name="input" v-model="myFormData.location"></textarea>
			</view>
			<view class="cu-form-group">
				<view class="title">经度</view>
				<input placeholder="请输入标题" name="input" v-model="myFormData.longitude"></input>
			</view>
			<view class="cu-form-group">
				<view class="title">纬度</view>
				<input placeholder="请输入标题" name="input" v-model="myFormData.dimension"></input>
			</view>
			<view class="cu-form-group">
			    <view class="title" >项目</view>
				<app-select  placeholder="请选择项目" :dict="plan_type" v-model="myFormData.projectId" @change="pickerChange"></app-select>
				<button
					style="width: 5rem;	background-color: #7ed084;color:white;border:0;font-size: 16px;border-radius: 30px;"
					@click="openLog"
				>
				日志</button>
			</view>
			<view class="cu-form-group">
				<view class="title">项目类别</view>
				<input placeholder="" name="input" v-model="projectType" disabled></input>
			</view>
			<view class="cu-form-group">
				<view class="title">设备数量</view>
				<input placeholder="" name="input" v-model="deviceNumber" disabled></input>
			</view>
			<view class="cu-form-group">
				<view class="title">第一责任人</view>
				<input placeholder="" name="input" v-model="personLiable" disabled></input>
			</view>
			<view class="cu-form-group">
				<view class="title">项目描述</view>
				<textarea  placeholder="" name="input"  v-model="projectDescription" disabled></textarea>
			</view>
			<view class="cu-form-group">
				<view class="title">现场照片</view>
				<view class="grid col-4 grid-square flex-sub">
					<view class="bg-img" v-for="(item,index) in tempFileList"  @tap="ViewImage(item.path,index)">
					<view class="feedback-image-item" :key="item.path">
						<image :src="item.path" class="feedback-image-icon"></image>
						<view class="cu-tag bg-red radius" @tap.stop="DelImg(index)">
							<text class='cuIcon-close'></text>
						</view>
					</view>
				</view>
				<view class="solids" @tap="ChooseImage">
					<text class='cuIcon-cameraadd'></text>
				</view>
				</view>
			</view>

			<view class="cu-form-group">
				<view class="title">现场视频</view>
				<view class="grid col-4 grid-square flex-sub">
					<view class="bg-img" v-show="showVideo" >
						<video :src="src" mode="aspectFill"  style="width: 130rpx;height: 130rpx;"></video>
					</view>
					<view class="solids" @tap="chooseVideo" >
						<text class='cuIcon-cameraadd'></text>
					</view>
				</view>
			</view>
			<view class="cu-form-group">
				<view class="title">本次上报安装设备数量</view>
				<view @click="reduce">-</view>

				<view style="width: 3rem;">
					<input style="text-align:center;" type="number" v-model="myFormData.installedNumber" @input="countVal"></input>
				</view>
				<view @click="adds">+</view>
			</view>
			<view class="cu-form-group">
				<view class="title">现场描述</view>
				<textarea  placeholder="输入描述" name="input"  v-model="myFormData.description"></textarea>
			</view>
			<view class="cu-form-group">
				<view class="title">上报时间:</view>
				<view class="uni-list-cell-db">
					<picker mode="date" :value="myFormData.reportTime" :start="startDate" :end="endDate" @change="bindDateChange">
						<view class="uni-input">{{myFormData.reportTime}}</view>
					</picker>
					</view>
					<view class="uni-list-cell-db">
					<picker mode="time" :value="myFormData.time" start="09:01" end="21:01" @change="bindTimeChange">
						<view class="uni-input">{{myFormData.time}}</view>
					</picker>
				</view>
			</view>
			<view class="padding flex flex-direction">
				<button class="cu-btn bg-blue lg"  @click="onSubmit">提交</button>
			</view>
		</form>
	</view>
</template>

<script>
	import appSelect from '@/components/my-componets/appSelect.vue'


	export default {
		components:{
			appSelect
		 },
		data() {
        const currentDate = this.getDate({
            format: true
        })
			return {
				tempFileList:[],
				index: -1,
				switchC: true,
				imgList: [],
				videoList: [],
				plan_type: [] ,
				type:"1",
				selected:[],
				src:"",//视频存放
				uploadUrl:"/api/v1/appbusiness/two/upload",
				uploadUrlVideo:"/api/v1/appbusiness/two/uploadVideo",
				cameraList: [{
				                        value: 'back',
				                        name: '后置摄像头',
				                        checked: 'true'
				                    },
				                    {
				                        value: 'front',
				                        name: '前置摄像头'
				                    },
				                ],
				cameraIndex: 0,
				showVideo:false,
				myFormData:{
					avatar:'',
					realname:'',
					username:'',
					description:'',
					id:'',
					emergencyTitle:'',
					reportPic:'',
					reportVideo:'',
					location:'',
					longitude:'',
					dimension:'',
					reportTime:currentDate,
					time: '12:01',
					projectId:'',
					installedNumber:0
				},
				projectId:'',
				projectDescription:'',
				personLiable:'',
				projectType:'',
				deviceNumber:'',
			};
		},
		onLoad: function (option) {

			var that=this;

			that.getRouteNew();

		  uni.getLocation({
			type: 'GCJ02',
		      success: function (res) {
		          console.log('经度：' + res.longitude);
		          console.log('纬度：' + res.latitude);
				  that.myFormData.longitude = res.longitude;
				  that.myFormData.dimension = res.latitude;
				  var point = new plus.maps.Point(res.longitude, res.latitude);
				  		plus.maps.Map.reverseGeocode(
				  			point,
				  			{},
				  			function(event) {
				  				var address = event.address; // 转换后的地理位置
				  				var point = event.coord; // 转换后的坐标信息
				  				var coordType = event.coordType; // 转换后的坐标系类型
				  				that.myFormData.location=address;
				  			},
				  			function(e) {}
				  		);
		      }
		  });

		  this.myFormData.time = this.getTime();
		  		console.log(this.myFormData.time);



		},
 computed: {
        startDate() {
            return this.getDate('start');
        },
        endDate() {
            return this.getDate('end');
        }
    },
		methods: {

			//减
			reduce(){
				if(this.myFormData.installedNumber !== 0){
				this.myFormData.installedNumber--;
				}

			},
			//加
			adds(){
				this.myFormData.installedNumber++;
			},
			//数值检测
			countVal(e){
				this.myFormData.installedNumber = e.detail.value;
				if(this.myFormData.installedNumber == 0){
					this.myFormData.installedNumber == 1
				}
			},


			openLog(){
				uni.navigateTo({
					url: '/pages/common/emergencyLog?item='+ encodeURIComponent(JSON.stringify(this.projectId))
				});
			},

			pickerChange(e){
				var that=this;
				that.projectId=e

				that.$http.get("/api/v1/appbusiness/two/findProjectRecord",{params:{projectId:that.projectId}}).then(res=>{
					console.log("-----------------",res.data.projectDescription)
					that.projectDescription=res.data.projectDescription
					that.personLiable=res.data.personLiable
					if(res.data.projectType === '1'){
						that.projectType='场站'
					} else if(res.data.projectType === '2'){
						that.projectType='远传'
					} else if(res.data.projectType === '3'){
						that.projectType='场站+远传'
					} else{
						that.projectType=''
					}
					that.deviceNumber=res.data.deviceNumber
				})

			},
			getRouteNew(){
				var that=this;
				that.$http.get("/api/v1/appbusiness/two/projectRecordList",{}).then(res=>{
			             that.plan_type =res.data

				})
			},

			getTime:function(){
						var date = new Date(),
						year = date.getFullYear(),
						month = date.getMonth() + 1,
						day = date.getDate(),
						hour = date.getHours() < 10 ? "0" + date.getHours() : date.getHours(),
						minute = date.getMinutes() < 10 ? "0" + date.getMinutes() : date.getMinutes(),
						second = date.getSeconds() < 10 ? "0" + date.getSeconds() : date.getSeconds();
						month >= 1 && month <= 9 ? (month = "0" + month) : "";
						day >= 0 && day <= 9 ? (day = "0" + day) : "";
						var timer = hour + ':' + minute + ':' + second;
						return timer;
					},
			bindTimeChange: function(e) {
			            this.myFormData.time = e.detail.value
			        },
        getDate(type) {
            const date = new Date();
            let year = date.getFullYear();
            let month = date.getMonth() + 1;
            let day = date.getDate();

            if (type === 'start') {
                year = year - 60;
            } else if (type === 'end') {
                year = year + 2;
            }
            month = month > 9 ? month : '0' + month;
            day = day > 9 ? day : '0' + day;
            return `${year}-${month}-${day}`;
        },
			bindDateChange: function(e) {
			    this.myFormData.reportTime = e.detail.value
			},
			onSubmit() {
			  let myForm = this.myFormData
			  console.log("myForm",myForm)
			  if(!myForm.emergencyTitle || myForm.emergencyTitle.length==0){
				this.$tip.alert('请填写现场标题');
				return false
			  }
			  if(!myForm.description || myForm.description.length==0){
			  				this.$tip.alert('请填写现场描述');
			  				return false
			  }
			  if(!myForm.projectId || myForm.projectId.length==0){
				this.$tip.alert('请选择项目');
				return false
			  }
				console.log('myform',this.myFormData)
				this.$tip.loading();
				this.$http.put('/api/v1/appbusiness/two/buildAdd',this.myFormData).then(res=>{
					console.log(res)
					this.$tip.loaded();
					if (res.data.success){
						this.$tip.toast('提交成功')
						let pages = getCurrentPages(); // 当前页面
						let beforePage = pages[pages.length - 2]; // 上一页
						uni.navigateBack({
						    success: function() {
						        beforePage.onLoad(); // 执行上一页的onLoad方法
						    }
						});
					}
				}).catch(()=>{
					this.$tip.loaded();
					this.$tip.error('提交失败')
				});
			},
			ChooseImage() {
				var that=this;
				uni.chooseImage({
					count: 9, //默认9
					sizeType: ['compressed'], //可以指定是原图还是压缩图，默认二者都有
					sourceType: ['album','camera'], //从相册选择
					success: (res) => {

					this.imgList = res.tempFilePaths  //这个是储存到当前页面显示的
					let tempFiles=res.tempFiles;
					tempFiles.forEach(function(item,index){
						console.log("-------------",item.name);
						console.log("-------------",item.path);
						that.tempFileList.push({
							name:item.name,
							path:item.path,
						})
					})

					let myimg = res.tempFilePaths;  //把数据直接插入到服务器  然后返回服务器的存储路径，然后插入到数据库
					for(let i = 0;i < myimg.length; i++) {
						console.info("------------myimg--",+myimg[i])
						that.$http.upload(that.$config.apiUrl+that.uploadUrl, {
								filePath: myimg[i],
								name: 'file'
							})
							.then(res => {
								/* that.myFormData.avatar=res.data.message; */
								console.log(res.data.message)
								let v = that.myFormData.reportPic;
								if(v==''){
									that.myFormData.reportPic=res.data.message;
								}else{
									that.myFormData.reportPic=v+','+res.data.message;
								}

							})
							.catch(err => {
								that.$tip.error(err.data.message)
							});
						}

					}
				});
			},
			chooseVideo(){
				var that=this;
			    // 上传视频
			    uni.chooseVideo({
			        maxDuration:60,
			        count: 1,
			        camera: this.cameraList[this.cameraIndex].value,
			    	sizeType: ['original'],
			        sourceType: ['album','camera'],
			        success: (res) => {
			            let videoFile = res.tempFilePath;
			    		that.src = res.tempFilePath;
			    		that.$http.upload(that.$config.apiUrl+that.uploadUrlVideo, {
			    			filePath: videoFile,
			    			name: 'file'
			    		})
			    		.then(res => {
			    			that.showVideo=true;
			    			/* this.src = res.data.message; */
			    			that.myFormData.reportVideo=res.data.message;
			    		})
			    		.catch(err => {
			    			that.$tip.error(err.data.message)
			    		});
			    	}
			    })
			},
			ViewImage(path,index) {
				uni.previewImage({
					urls:this.imgList,
					current: index
				});
			},
			DelImg(index) {
				uni.showModal({
					title: '你好',
					content: '确定要删除这张图片吗？',
					cancelText: '取消',
					confirmText: '确认',
					success: res => {
						if (res.confirm) {
							console.log("myFormData[删除图片]下标----",index)
							this.tempFileList.splice(index,1)
							console.log(this.tempFileList)

							var picString = this.myFormData.reportPic;
							var m = picString.split(",");
							for(let l = 0;l < m.length; l++){
								console.log("myFormDatareportPic返回给后端数据删除前  "+m[l]);
							}
							m.splice(index,1);
							var reporePic=null;
							for(let i = 0;i < m.length; i++){
								if(reporePic==null){
									reporePic=m[i];
								}else{
									reporePic=reporePic+','+m[i];
								}
								console.log("myFormDatareportPic返回给后端数据删除后  "+m[i]);
							}
							this.myFormData.reportPic=reporePic

							console.log("拼接完成返回给后端数据  "+this.myFormData.reportPic);
						}
					}
				})
			}

		}
	}
</script>

<style>
	.cu-form-group .title {
		min-width: calc(4em + 15px);
	}
	.burst-wrap{
	    width: 100%;
	    height: 100%;
	}
	.burst-wrap .burst-wrap-bg>view{
	    width: 90%;
	    height: 100%;
	    margin: 0 auto;
	    position: absolute;
	    top: 65upx;
	    left: 0;
	    right: 0;
	}

	.form-item{
	    width: 100%;
	}
	.form-item textarea{
	    display: block;
	    height: 220upx;
	    width: 100%;
	    color: #AAAAAA;
	    font-size: 28upx;
	}
	.uni-uploader__file,.uploader_video{
	    position: relative;
	    z-index: 1;
	    width: 200upx;
	    height: 200upx;
	}
	.uni-uploader__img {
	    width: 200upx;
	    height: 200upx;
	}
	.icon-cuo {
	    position: absolute;
	    right: 0;
	    top: 5upx;
	    background: linear-gradient(90deg,rgba(251,91,80,1) 0%,rgba(240,45,51,1) 100%);
	    color: #FFFFFF;
	    z-index: 999;
	    border-top-right-radius: 20upx;
	    border-bottom-left-radius: 20upx;
	}
	.video{
	    width: 100%;
	    height: 100%;
	}

	.login-input-box{
	    position: relative;
	    border-bottom: 1upx solid #EEEEEE;
	}
	.login-input-box .forget,.login-input-box .phone{
	    position: absolute;
	    top: 0;
	    height: 100%;
	    z-index: 100;
	}
	.login-input-box .phone{
	    width: 100upx;
	    left: 0;
	    color: #666666;
	    font-weight: bold;
	}
	.login-input-box .phone-input{
	    padding-left: 100upx;
	}
	.address-wrap,.open-info{
	    margin-top: 20upx;
	}
	.open-info>view:last-child{
	    font-size: 28upx;
	    color: #999999;
	}
	.address-wrap .address {
	    background: #F2F2F2;
	    border-radius: 40upx;
	    padding: 0 20upx;
	}
	.user-set-btn{
	    margin: 40upx;
	    background: linear-gradient(90deg,rgba(251,91,80,1) 0%,rgba(240,45,51,1) 100%);
	    color: #FFFFFF;
	    text-align: center;
	    height: 88upx;
	    line-height: 88upx;
	}

</style>
